package com.zbvc.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zbvc.dao.AdminDao;
import com.zbvc.dao.impl.AdminDaoImpl;
import com.zbvc.entity.Admin;

/**
 * 用户登录
 */
@WebServlet(name = "login", urlPatterns = { "/login" })
public class LoginServlet extends HttpServlet {
	
	private AdminDao adminDao= new AdminDaoImpl();
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public LoginServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		boolean result = adminDao.login(username, password);
		HttpSession session = request.getSession(); // 创建session会话
		if (result) {
			Admin admin = new Admin();
			admin = adminDao.getAdminInfo(username, password);
			// 将用户id存入session
			session.setAttribute("aid", admin.getAid());
			// 设置session失效时间
			session.setMaxInactiveInterval(6000000);
			// 根据status的值判断是否时管理员
			if (admin.getStatus()==1) {
				response.sendRedirect("/book-manager/index2.jsp");
			}else {
				response.sendRedirect("/book-manager/admin/admin.jsp");
			}
			
		}else {
			session.setAttribute("errorMsg", "用户名或密码错误！");
			response.sendRedirect("/book-manager/login.jsp");
		}
		
	}

}
